import { DeleteOutlined, EditFilled, PlusOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import {ProTable, ModalForm, ProFormSwitch, ProFormText, ProFormTreeSelect} from '@ant-design/pro-components';
import {Button, message, Popconfirm, Switch} from 'antd';
import React, { useRef, useState } from 'react';

import { RequestOptionsType } from '@ant-design/pro-utils';
import type { MenuItem } from './data';
import { addMenu, deleteMenu, queryMenu, updateMenu } from './service';
import {ProFormDigit} from "@ant-design/pro-form";

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: MenuItem) => {
  const hide = message.loading('正在添加...');

  try {
    const res = await addMenu({ ...fields });
    if (res && res.status === 'done') {
      hide();
      message.success(res.message);
      return true;
    } else {
      hide();
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: MenuItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteMenu({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  // ModalForm更新入口
  const formRef = useRef<ProFormInstance>();

  // 表头，列表渲染设置
  // @ts-ignore
  const columns: ProColumns<MenuItem>[] = [
    // 列表字段
    // 菜单名
    {
      title: '菜单名称',
      dataIndex: 'title',
      valueType: 'text',
      hideInSearch: true,
    },
    // icon
    {
      title: 'Icon',
      dataIndex: 'icon',
      valueType: 'text',
      hideInSearch: true,
      tooltip: '二级以下菜单，不支持设置ICON',
    },
    // url
    {
      title: '路由',
      dataIndex: 'url',
      valueType: 'text',
      hideInSearch: true,
    },
    // 权限标志
    {
      title: '权限标志',
      dataIndex: 'privilegeName',
      valueType: 'text',
      hideInSearch: true,
    },
    // 权限标志
    {
      title: '排序号',
      dataIndex: 'orderNum',
      valueType: 'digit',
      hideInSearch: true,
      tooltip: '越大排越后',
    },
    // 是否展示
    {
      title: '显示',
      dataIndex: 'show',
      sorter: true,
      hideInSearch: true,
      valueType: 'switch',
      fieldProps: {
        checkedChildren: '显示',
        unCheckedChildren: '隐藏',
      },
      render: (_, { show }) => (
        <Switch disabled checkedChildren={'显示'} checked={show} unCheckedChildren={'隐藏'} />
      ),
    },
    {
      title: '操作',
      key: 'option',
      align: 'right',
      valueType: 'option',
      width: 120,
      render: (_, record, __, action) => [
        // 修改
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          <EditFilled />
          修改
        </a>,
        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
          const success = await handleSingleRemove(record);
          if (success) {
            actionRef?.current?.reload();
          }
        }}>
          <a style={{color: "red"}} ><DeleteOutlined /> 删除</a>
        </Popconfirm>
      ],
    },
  ];

  return (
    <PageContainer breadcrumbRender={false}>
      <ProTable<MenuItem>
        pagination={false}
        headerTitle="菜单列表"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        editable={{
          type: 'multiple',
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.save, defaultDoms.cancel];
          },
          onSave: async (rowKey, data) => {
            try {
              const res = await updateMenu({
                ...data,
              });
              if (res && res.status === 'done') {
                message.success(res.message);
                return true;
              } else {
                message.error(res.message);
                return false;
              }
            } catch (error) {
              message.error('更新失败，请重试！');
              return false;
            }
          },
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        // 表格数据源
        // @ts-ignore
        request={queryMenu}
        columns={columns}
      />
      <ModalForm
        title="新增菜单"
        width="600px" // 注销可由其自动管理宽度
        formRef={formRef}
        open={createModalVisible}
        onOpenChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as MenuItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormTreeSelect
          label="上级节点，不选默认为添加顶级菜单"
          width="xl"
          name="pid"
          allowClear={true}
          fieldProps={{
            filterTreeNode: true,
            showSearch: true, // 搜索功能
            multiple: false, // 多选
            // treeDefaultExpandAll: true,   // 默认展开所有节点
            treeCheckable: false, // 选项前增加复选框，如果增加复选框，选中父节点时，子节点也会同步勾选
            // treeDefaultExpandedKeys: [1], // 只展开1级节点（2级节点可见）
            treeNodeFilterProp: 'title', // 设置支持搜索中文（title）, 默认根据value来搜索的
            removeIcon: true,
          }}
          // 动态请求后端数据，形成Option
          request={async () => {
            const params = await queryMenu();
            let res:
              | RequestOptionsType[]
              | PromiseLike<RequestOptionsType[]>
              | { label: any; value: any }[] = [];
            if (params.success) {
              res = params.data;
            }
            return res;
          }}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单名称为必填项',
            },
          ]}
          width="xl"
          name="title"
          label={'菜单名称'}
        />
        <ProFormText width="xl" name="icon" label={'ICON'} />
        <ProFormText
          rules={[
            {
              required: true,
              message: '路由Url为必填项',
            },
          ]}
          width="xl"
          name="url"
          label={'路由'}
          placeholder={'若仅做权限标志，请输入#'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '权限标识为必填项',
            },
          ]}
          width="xl"
          name="privilegeName"
          label={'权限标识'}
          placeholder={'需全局唯一'}
        />
        <ProFormDigit
          width="xl"
          name="orderNum"
          label={'排序号'}
          initialValue={1000}
          tooltip={'越小越靠前'}
        />
        <ProFormSwitch
          name="show"
          checkedChildren={'显示'}
          unCheckedChildren={'隐藏'}
          initialValue={true}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
